package org.jsets.fastboot.persistent.support;

import static java.util.stream.Collectors.joining;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import org.jsets.fastboot.persistent.IPageRequest;
import com.baomidou.mybatisplus.core.conditions.AbstractLambdaWrapper;
import com.baomidou.mybatisplus.core.conditions.SharedString;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;

@SuppressWarnings("serial")
public class LambdaQuerier<T> extends AbstractLambdaWrapper<T, LambdaQuerier<T>> implements Query<LambdaQuerier<T>, T, SFunction<T, ?>> {

    /**
     * 查询字段
     */
    private SharedString sqlSelect = new SharedString();
    
    private BaseMapper<T> baseMapper;
    protected Page<T> page;

    public LambdaQuerier() {
        this((T) null);
    }

    public LambdaQuerier(T entity) {
        super.setEntity(entity);
        super.initNeed();
    }

    public LambdaQuerier(Class<T> entityClass) {
        super.setEntityClass(entityClass);
        super.initNeed();
    }

    public static <T> LambdaQuerier<T> build() {
        return new LambdaQuerier<>();
    }
    
    public static <T> LambdaQuerier<T> build(T entity) {
        return new LambdaQuerier<>(entity);
    }
    
    public static <T> LambdaQuerier<T> build(Class<T> entityClass) {
        return new LambdaQuerier<>(entityClass);
    }
    
    /**
     * 不建议直接 new 该实例，使用 Wrappers.lambdaQuery(...)
     */
    LambdaQuerier(T entity, Class<T> entityClass, SharedString sqlSelect, AtomicInteger paramNameSeq,
                       Map<String, Object> paramNameValuePairs, MergeSegments mergeSegments,
                       SharedString lastSql, SharedString sqlComment, SharedString sqlFirst) {
        super.setEntity(entity);
        super.setEntityClass(entityClass);
        this.paramNameSeq = paramNameSeq;
        this.paramNameValuePairs = paramNameValuePairs;
        this.expression = mergeSegments;
        this.sqlSelect = sqlSelect;
        this.lastSql = lastSql;
        this.sqlComment = sqlComment;
        this.sqlFirst = sqlFirst;
    }

    /**
     * SELECT 部分 SQL 设置
     *
     * @param columns 查询字段
     */
    @SafeVarargs
    @Override
    public final LambdaQuerier<T> select(SFunction<T, ?>... columns) {
        if (ArrayUtils.isNotEmpty(columns)) {
            this.sqlSelect.setStringValue(columnsToString(false, columns));
        }
        return typedThis;
    }

    /**
     * 过滤查询的字段信息(主键除外!)
     * <p>例1: 只要 java 字段名以 "test" 开头的             -> select(i -&gt; i.getProperty().startsWith("test"))</p>
     * <p>例2: 只要 java 字段属性是 CharSequence 类型的     -> select(TableFieldInfo::isCharSequence)</p>
     * <p>例3: 只要 java 字段没有填充策略的                 -> select(i -&gt; i.getFieldFill() == FieldFill.DEFAULT)</p>
     * <p>例4: 要全部字段                                   -> select(i -&gt; true)</p>
     * <p>例5: 只要主键字段                                 -> select(i -&gt; false)</p>
     *
     * @param predicate 过滤方式
     * @return this
     */
    @Override
    public LambdaQuerier<T> select(Class<T> entityClass, Predicate<TableFieldInfo> predicate) {
        if (entityClass == null) {
            entityClass = getEntityClass();
        } else {
            setEntityClass(entityClass);
        }
        Assert.notNull(entityClass, "entityClass can not be null");
        this.sqlSelect.setStringValue(TableInfoHelper.getTableInfo(entityClass).chooseSelect(predicate));
        return typedThis;
    }

    /**
     * 排除列
     * @param columns 列
     * @return
     */
    @SafeVarargs
    public final LambdaQuerier<T> excludes(SFunction<T, ?>... columns) {
    	if(null==this.getEntityClass()) {
    		return typedThis;
    	}
    	
    	TableInfo tableInfo = TableInfoHelper.getTableInfo(this.getEntityClass());
        String sqlSelect = tableInfo.getKeySqlSelect();
        String fieldsSqlSelect = tableInfo
        		.getFieldList()
        		.stream()
        		.filter(f->{
        			boolean isInclude = true;
        			for(SFunction<T, ?> column: columns) {
        				if(f.getColumn().equals(columnToString(column))) {
        					isInclude = false;
        					break;
        				}
        			}
        			return isInclude;
        		})
        		.map(TableFieldInfo::getSqlSelect)
        		.collect(joining(TableInfo.COMMA));
        if (StringUtils.isNotBlank(sqlSelect) && StringUtils.isNotBlank(fieldsSqlSelect)) {
        	sqlSelect =  sqlSelect + TableInfo.COMMA + fieldsSqlSelect;
        } else if (StringUtils.isNotBlank(fieldsSqlSelect)) {
        	sqlSelect =  fieldsSqlSelect;
        }
        
        this.sqlSelect.setStringValue(sqlSelect);
        return typedThis;   
    }

    @Override
    public String getSqlSelect() {
        return sqlSelect.getStringValue();
    }

    /**
     * 用于生成嵌套 sql
     * <p>故 sqlSelect 不向下传递</p>
     */
    @Override
    protected LambdaQuerier<T> instance() {
        return new LambdaQuerier<>(getEntity(), getEntityClass(), null, paramNameSeq, paramNameValuePairs,
            new MergeSegments(), SharedString.emptyString(), SharedString.emptyString(), SharedString.emptyString());
    }

    @Override
    public void clear() {
        super.clear();
        sqlSelect.toNull();
    }
    
	private synchronized <E extends IPage<T>> E getOrCreatePage() {
		if(this.page == null) {
			this.page = new Page<T>();
		}
		return (E) this.page;
	}
    
	public LambdaQuerier<T> setCurrentPage(Integer currentPage) {
		if(currentPage !=null) {
			this.getOrCreatePage().setCurrent(currentPage);
		}
		return typedThis;
	}

	public LambdaQuerier<T> setPageSize(Integer pageSize) {
		if(pageSize !=null) {
			getOrCreatePage().setSize(pageSize);
		}
		return typedThis;
	}
	
	public LambdaQuerier<T> setPageCriteria(IPageRequest pageRequest) {
		getOrCreatePage().setCurrent(pageRequest.getCurrent());
		getOrCreatePage().setSize(pageRequest.getSize());
		return typedThis;
	}
    
    public LambdaQuerier<T> setBaseMapper(BaseMapper<T> baseMapper) {
		this.baseMapper = baseMapper;
		return typedThis;
	}
    
	/**
     * <p>
     * 查询一条记录
     * </p>
     * 
     * @return T
     * 
	 * 
	 */
    public T selectOne() {
    	return this.baseMapper.selectOne(this);
    }
    
	/**
     * <p>
     * 查询一条记录
     * </p>
     * 
     * @return T
     */
    public Optional<T> findOne() {
    	return Optional.ofNullable(this.baseMapper.selectOne(this));
    }
    
    /**
     * <p>
     * 根据 Wrapper 条件，查询总记录数
     * </p>
     * 
     * @return int
     */
    public int selectCount() {
    	return SqlHelper.retCount(baseMapper.selectCount(this));
    }
    
    /**
     * <p>
     * 查询列表
     * </p>
     * 
     * @return List<T>
     */
    public List<T> selectList(){
    	return baseMapper.selectList(this);
    }
    
    /**
     * <p>
     * 翻页查询
     * </p>
     *
     * @return
     */ 
    public <E extends IPage<T>> E selectPage(E page){
    	Objects.requireNonNull(page);
    	
        E ipage = baseMapper.selectPage(page, this);
        return ipage;
    }
    
    /**
     * <p>
     * 翻页查询
     * </p>
     *
     * @return
     */ 
    public <E extends IPage<T>> E selectPage(){
        E ipage = baseMapper.selectPage(this.getOrCreatePage(), this);
        return ipage;
    }
    
    /**
     * 如果 val 为null则不加入查询条件
     * <br>
     * 如果 val 为字符串，则空串也不加入查询条件
     * @param column 列名称
     * @param val 值
     * @return QueryActuator<T>
     */
    public LambdaQuerier<T> eqIfNecessary(SFunction<T, ?> column, Object val) {
    	if(this.isNecessary(val)) {
    		this.eq(column, val);
    	}
    	return typedThis;
    }
    
    /**
     * 如果 val 为null则不加入查询条件
     * <br>
     * 如果 val 为字符串，则空串也不加入查询条件
     * @param column 列名称
     * @param val 值
     * @return QueryActuator<T>
     */
    public LambdaQuerier<T> likeIfNecessary(SFunction<T, ?> column, Object val) {
    	if(this.isNecessary(val)) {
    		this.like(column, val);
    	}
    	return typedThis;
    }
    
    /**
     * LIKE '%值'
     * <br>
     * 如果 val 为null则不加入查询条件
     * <br>
     * 如果 val 为字符串，则空串也不加入查询条件
     * @param column 列名称
     * @param val 值
     * @return QueryActuator<T>
     */
    public LambdaQuerier<T> likeLeftIfNecessary(SFunction<T, ?> column, Object val) {
    	if(this.isNecessary(val)) {
    		this.likeLeft(column, val);
    	}
    	return typedThis;
    }
    
    /**
     * LIKE '值%'
     * <br>
     * 如果 val 为null则不加入查询条件
     * <br>
     * 如果 val 为字符串，则空串也不加入查询条件
     * @param column 列名称
     * @param val 值
     * @return QueryActuator<T>
     */
    public LambdaQuerier<T> likeRightIfNecessary(SFunction<T, ?> column, Object val) {
    	if(this.isNecessary(val)) {
    		this.likeRight(column, val);
    	}
    	return typedThis;
    }
    
    /**
     * 如果 val 为null则不加入查询条件
     * <br>
     * 如果 val 为字符串，则空串也不加入查询条件
     * @param column 列名称
     * @param val 值
     * @return QueryActuator<T>
     */
    public LambdaQuerier<T> geIfNecessary(SFunction<T, ?> column, Object val) {
    	if(this.isNecessary(val)) {
    		this.ge(column, val);
    	}
    	return typedThis;
    }
    
    /**
     * collection为null不加入查询条件
     * <br>
     * collection的size为0也不加入查询条件
     * @param column 列名称
     * @param collection 集合
     * @return QueryActuator<T>
     */
    public LambdaQuerier<T> inIfNecessary(SFunction<T, ?> column, Collection<?> collection) {
    	if(this.isNecessary(collection)) {
    		this.in(column, collection);
    	}
    	return typedThis;
    }
    
    /**
     * collection为null不加入查询条件
     * <br>
     * collection的size为0也不加入查询条件
     * @param column 列名称
     * @param collection 集合
     * @return QueryActuator<T>
     */
    public LambdaQuerier<T> notInIfNecessary(SFunction<T, ?> column, Collection<?> collection) {
    	if(this.isNecessary(collection)) {
    		this.notIn(column, collection);
    	}
    	return typedThis;
    }
    
    private boolean isNecessary(Object val) {
    	if(null==val) {
    		return false;
    	}
    	
    	if(val instanceof String) {
    		String str = (String)val;
    		if("".equals(str)) {
    			return false;
    		}
    	}
    	
    	if(val instanceof Collection) {
    		Collection collection = (Collection)val;
    		if(collection.size()==0) {
    			return false;
    		}
    	}
    	
    	return true;
    }
    
}
